package com.mixsmart.core.xml.validator;

import java.io.File;
import java.io.InputStream;
import java.net.URL;

import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;

import org.apache.commons.lang3.StringUtils;
import org.xml.sax.SAXException;

/**
 * SQLMap验证类；该类为单例
 * 调用方式为： SqlMapValidator.getInstance("xxxx")
 * @author lmq
 * @version 1.0
 * @since JDK版本大于等于1.6
 * 2016年1月20日
 */
public class SqlMapValidator extends AbstractXmlValidator {
	
	private Validator validator;
	
	private String xmlFile;
	
	private static SqlMapValidator instance;
	
	private SqlMapValidator(String xmlFile) {
		this.xmlFile = xmlFile;
		this.init();
	}
	
	private void init() {
		SchemaFactory factory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
		URL url = this.getClass().getResource("/sqlmap.xsd");
		File file = new File(url.getPath());
		try {
			Schema schema = factory.newSchema(file);
			validator = schema.newValidator();
		} catch (SAXException e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * 获取SqlMapValidator实例
	 * @param xmlFile 
	 * @return 返回SqlMapValidator实例
	 */
	public synchronized static SqlMapValidator getInstance(String xmlFile) {
		if(null == instance) {
			instance = new SqlMapValidator(xmlFile);
		}
		return instance;
	}
	
	/**
	 * 设置配置文件
	 * @param xmlFile
	 */
	public void setXmlFile(String xmlFile) {
		if(StringUtils.isNotEmpty(xmlFile)) {
			this.xmlFile = xmlFile;
		} else {
			this.xmlFile = null;
		}
	}
	
	@Override
	public boolean validator() throws Exception {
		boolean is = false;
		if(StringUtils.isEmpty(xmlFile)) {
			throw new Exception("xmlFile为空");
		}
		InputStream inputStream = this.getClass().getResourceAsStream("/"+this.xmlFile);
		Source source = new StreamSource(inputStream);
		try {
			validator.validate(source);
			is = true;
		} catch (SAXException ex) {
			System.out.println(xmlFile + " is not valid because ");
			logger.error(ex.getMessage());
			is = false;
		}
		return is;
	}
	
	/**
	 * 摧毁SqlMapValidator对象实例
	 */
	public void destory() {
		instance = null;
		validator = null;
	}

}
